<template>
	<div class="tables">
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
			<el-form-item label="频道名称">
				<el-input v-model="formInline.name" placeholder="请输入频道名称" clearable />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="onSubmit">搜索</el-button>
				<el-button :icon="Refresh" @click="onreset">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="mb-4">
			<el-button :icon="Plus" type="primary" plain @click="addData">新增</el-button>
			<!-- <el-button :icon="EditPen" type="success" @click="editData" plain>修改</el-button> -->

			<el-popconfirm title="确定删除所选内容吗？" @confirm="deleteElement">
				<template #reference>
					<el-button :icon="Delete" type="danger" plain>批量删除</el-button>
				</template>
			</el-popconfirm>
		</div>

		<el-table v-loading="loading" ref="multipleTableRef" :data="tableData" style="width: 100%;margin-top: 20px;"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" :selectable="selectable" width="55" />
			<el-table-column v-for="column in pageData.columns" :sortable="column.prop=='classfiyname'"
				:key="column.prop" :prop="column.prop" :label="column.label" :min-width="column.minWidth">
				<!-- <template v-if="column.prop=='channelicon'" #default="scope">
					<img style="height: 30px;" :src="channeliconurl(scope.row.channelicon)" alt="" />
				</template> -->
			</el-table-column>
			<el-table-column label="操作" class="notranslate">
				<template #default="scope">
					<el-dropdown>
						<el-button>操作</el-button>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item @click="editeRowData(scope.row)">
									<icon name="bianji" />修改
								</el-dropdown-item>
								<el-dropdown-item @click="deleteRowData(scope.row)">
									<icon name="shanchu" />删除
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>

		<div class="pagination">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20]"
				:size="size" :disabled="disabled" :background="background"
				layout="total, sizes, prev, pager, next, jumper" :total="totals" locale="zh_CN"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>

		<div class="wxdialog">
			<el-dialog @close="closedialog" v-model="dialogVisible" :title="Tips?'新增':'修改'" width="900" draggable>
				<div>
					<el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" :rules="rules"
						label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
						<el-form-item label="标题">
							<el-input v-model="ruleForm.title" placeholder="请填写标题" />
						</el-form-item>
						
						<el-form-item label="选择分类">
							<el-select
							      v-model="ruleForm.classfiy"
							      multiple
							      placeholder="选择分类"
							      style="width: 240px"
							    >
							      <el-option
							        v-for="item in classoptions"
							        :key="item.value"
							        :label="item.label"
							        :value="item.value"
							      />
							    </el-select>
						</el-form-item>
						<el-form-item label="图床">
							<el-input v-model="ruleForm.img" placeholder="请填写图片链接" />
						</el-form-item>
						<el-form-item label="图片">
							<el-upload class="avatar-uploader" :action="uploadHost"
								:show-file-list="false" :on-success="handleSuccess"
								:before-upload="beforeUpload">
								<img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus />
								</el-icon>
							</el-upload>
						</el-form-item>
						<el-form-item label="内容">
							<Toolbar
							        style="border-bottom: 1px solid #ccc"
							        :editor="editorRef"
							        :defaultConfig="toolbarConfig"
							        :mode="mode"
							      />
							<Editor
							        style="height: 500px; overflow-y: hidden;"
							        v-model="ruleForm.content"
							        :defaultConfig="editorConfig"
							        :mode="mode"
							        @onCreated="handleCreated"
							      />
						</el-form-item>
						
					</el-form>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="resetForm(ruleFormRef)">取消</el-button>
						<el-button type="primary" @click="submitForm(ruleFormRef)">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>
		</div>

	</div>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted, getCurrentInstance, computed,shallowRef,onBeforeUnmount} from 'vue'
	import type { TableInstance, ComponentSize, FormInstance, FormRules } from 'element-plus'
	import { Search, Refresh, Plus, EditPen, Delete, Download } from '@element-plus/icons-vue'
	import '@wangeditor/editor/dist/css/style.css' // 引入 css
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
	
	// 编辑器实例，必须用 shallowRef
	    const editorRef = shallowRef()
	    const toolbarConfig = {}
	    const editorConfig = { placeholder: '请输入内容...' }
		const mode=ref('default')// 或 'simple'
	    // 组件销毁时，也及时销毁编辑器
	    onBeforeUnmount(() => {
	        const editor = editorRef.value
	        if (editor == null) return
	        editor.destroy()
	    })
	
	    const handleCreated = (editor) => {
	      editorRef.value = editor // 记录 editor 实例，重要！
	    }
		
		const classoptions = [
		  {
		    value: '0',
		    label: '儿童笑话',
		  },
		  {
		    value: '1',
		    label: '内涵段子',
		  },
		  {
		    value: '2',
		    label: '校园笑话',
		  },
		  {
		    value: '3',
		    label: '动物笑话',
		  },
		  {
		    value: '4',
		    label: '职场笑话',
		  },
		  {
		    value: '5',
		    label: '神回复',
		  },
		  {
		    value: '6',
		    label: '家庭笑话',
		  },
		  {
		    value: '7',
		    label: '搞笑对话',
		  },
		]
		
	
	
	const currentPage = ref(1)
	const pageSize = ref(10)
	let totals = ref<number>(0)
	const size = ref<ComponentSize>('default')
	const background = ref(true)
	const disabled = ref(false)
	let dialogVisible = ref(false)
	const loading = ref(true)
	const Tips = ref(true)
	const { proxy } = getCurrentInstance();
	const uploadHost = proxy.Uploadhostmini;
	let currentrow = reactive({})
	let valueHtml = ref()
	const pageData = reactive({
		columns: [
			{
				prop:'content',
				label:'内容'
			}
		]
	});
	
	import type { UploadProps } from 'element-plus'
	
	const imageUrl = ref('')
	
	const handleSuccess: UploadProps['onSuccess'] = (
	  response,
	  uploadFile
	) => {
	  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
	  ruleForm.img='https://www.zhaowenjing.com/mini/'+response.data[0]
	}
	
	const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
	  
	  return true
	}
	
	const channeliconurl = computed(()=>{
		return (item) => proxy.imgHost + `${item}`;
	})

	let classfiy = ref([])

	// const getclassify = () => {
	// 	proxy.$http.get('/mini/getclassfiy').then((res) => {
	// 		classfiy.value = res.data
	// 	}).catch((error) => {
	// 		console.log(error)
	// 	})
	// }
	
	const getFilm=()=>{
		proxy.$http.post('/film/getfilmsByid',{id:1,currentPage:currentPage.value,pageSize:pageSize.value}).then((res) => {
			console.log(res)
			// classfiy.value = res.data
		}).catch((error) => {
			console.log(error)
		})
	}

	const getchannel = () => {
		proxy.$http.post('/mini/getbaoxiao',{currentPage:currentPage.value,pageSize:pageSize.value}).then((res) => {
			tableData.value = res.data;
			totals.value = res.totals;
		}).catch((error) => {
			console.log(error)
		})
	}

	interface User {
		id : number
		classfiyname : string
		classfiyid : number
		name : string
		channelicon:string
	}

	let tableData : User[] = ref([])
	onMounted(() => {
		// getclassify()
		getchannel()
		// getFilm()
	})

	setTimeout(() => {
		loading.value = false
	}, 2000)


	const formSize = ref<ComponentSize>('default')
	const ruleFormRef = ref(null)
	let ruleForm = reactive({
		title:'',
		content:'',
		img:'',
		classfiy:''
	})
	
	const closedialog=()=>{
		// imageUrl.value = ""
		// ruleForm.classfiyid=null,
		// ruleForm.name= '',
		// ruleForm.classfiyname="",
		// ruleForm.channelicon=''
	}

	const rules = reactive({
		
	})

	const submitForm = async (formEl : FormInstance | undefined) => {
		console.log(valueHtml)
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				if (Tips.value) { //新增
					ruleForm.classfiy=JSON.stringify(ruleForm.classfiy)
					proxy.$http.post('/mini/addbaoxiao', ruleForm).then((res) => {
						getchannel()
						dialogVisible.value = false
						formEl.resetFields()
						ruleForm.content=""
						ruleForm.img=""
						ruleForm.title=""
						ruleForm.classfiy=""
					}).catch((error) => {
						console.log(error)
					})
				} else {
					ruleForm.classfiy=JSON.stringify(ruleForm.classfiy)
					proxy.$http.post('/mini/updatebaoxiao', ruleForm).then((res) => {
						getchannel()
						dialogVisible.value = false
						formEl.resetFields()
					}).catch((error) => {
						console.log(error)
					})
				}

			} else {

				console.log('error submit!', fields)
				return false
			}
		})

	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		dialogVisible.value = false
	}

	const options = Array.from({ length: 10000 }).map((_, idx) => ({
		value: `${idx + 1}`,
		label: `${idx + 1}`,
	}))

	const handleSizeChange = (val : number) => {
		
	}
	const handleCurrentChange = (val : number) => {
		console.log(`current page: ${val}`)
		proxy.$http.post('/mini/getbaoxiao', { "currentPage": val, "pageSize": pageSize.value }).then((res) => {
			console.log(res)
			tableData.value = res.data;
			totals.value = res.totals;
		}).catch((error) => {
			console.log(error)
		})
	}

	const addData = () => {
		Tips.value = true
		dialogVisible.value = true

	}

	const editeRowData = (row) => {
		console.log(row)
		Tips.value = false
		dialogVisible.value = true
		ruleForm.title=row.title
		ruleForm.content=row.content
		ruleForm.img=row.img
		imageUrl.value=row.img
		ruleForm.classfiy=row.classfiy
		ruleForm.id=row.id
		currentrow = row;
	}

	const deleteRowData = (row) => {
		proxy.$http.post('/mini/deletebaoxiao', { "id": row.id }).then((res) => {
			getchannel()
		}).catch((error) => {
			console.log(error)
		})
	}

	const editData = () => {
		Tips.value = false
		dialogVisible.value = true
	}

	const formInline = reactive({
		name: '',
	})

	const onSubmit = () => {
		const obj={
			name:formInline.name,
			currentPage:currentPage.value,
			pageSize:pageSize.value
		}
		proxy.$http.post('/searchTablechannel',obj).then((res)=>{
			// tableData.value=res.data;
		}).catch((err)=>{
			console.log(err)
		})
	}

	const onreset = () => {
		formInline.name = "";
	}

	const multipleTableRef = ref<TableInstance>()
	const multipleSelection = ref<User[]>([])

	const selectable = (row : User) => ![].includes(row.id)
	const toggleSelection = (rows ?: User[], ignoreSelectable ?: boolean) => {
		if (rows) {
			rows.forEach((row) => {
				multipleTableRef.value!.toggleRowSelection(
					row,
					undefined,
					ignoreSelectable
				)
			})
		} else {
			multipleTableRef.value!.clearSelection()
		}
	}
	const handleSelectionChange = (val : User[]) => {
		multipleSelection.value = val
	}

	const deleteElement = () => {
		const newobj = multipleSelection.value.map((item) => {
			return item.id
		})
		proxy.$http.post('/deletechannel', { "id": newobj }).then((res) => {
			getchannel()
		}).catch((error) => {
			console.log(error)
		})
	}
</script>
<style scoped>
	.tables {
		/* width: 98%; */
		margin: 20px auto;
		padding: 20px;
		box-sizing: border-box;
		background: #fff;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	/deep/ .el-table th.el-table__cell {
		background-color: #f8f8f8;
	}

	/deep/ .el-dropdown {
		color: #409eff;
		cursor: pointer;
	}

	/deep/ .el-table .cell {
		line-height: unset;
		/* cursor: pointer; */
	}

	/deep/ .el-popup-parent--hidden {
		width: 100% !important;
	}

	.demo-pagination-block+.demo-pagination-block {
		margin-top: 10px;
	}

	.demo-pagination-block .demonstration {
		margin-bottom: 16px;
	}

	.pagination {
		margin: 20px auto;
		display: flex;
		justify-content: flex-end;
	}
	
	.avatar-uploader .avatar {
	  width: 178px;
	  height: 178px;
	  display: block;
	}
	
	.avatar-uploader .el-upload {
	  border: 1px dashed var(--el-border-color);
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	  transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
	  border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
	  font-size: 28px;
	  color: #8c939d;
	  width: 178px;
	  height: 178px;
	  text-align: center;
	  border: 1px dashed;
	}
	::v-deep .w-e-text-container .w-e-scroll{
		width: 800px;
	}
</style>